package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"zg3/user-modules/internal/dao"
	"zg3/user-modules/internal/model"
)

type WsReq struct {
	Cmd  string      `json:"cmd"`
	Data interface{} `json:"data"`
}
type Send struct {
	ToUserId uint   `json:"to_user_id"`
	Content  string `json:"content"`
}
type SendReq struct {
	Cmd  string `json:"cmd"`
	Data Send   `json:"data"`
}
type WsResp struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

var OnlineUserMap = make(map[uint]*websocket.Conn)

func WebsocketChat(c *gin.Context) {
	var upgrader = websocket.Upgrader{} // use default options

	coon, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer coon.Close()

	OnlineUserMap[c.GetUint("userId")] = coon
	fmt.Println(OnlineUserMap)

	for {
		_, message, err := coon.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		var req WsReq
		err = json.Unmarshal(message, &req)
		if err != nil {
			GetFailResp(coon, 500, "指令解析失败")
			continue
		}
		switch req.Cmd {
		case "send":
			sendUser(coon, message, c.GetUint("userId"))
		default:
			GetFailResp(coon, 500, "没有该指令")
		}
	}
}

func sendUser(coon *websocket.Conn, message []byte, userId uint) {
	var req SendReq
	err := json.Unmarshal(message, &req)
	if err != nil {
		GetFailResp(coon, 500, "发送信息指令错误")
		return
	}
	toUserId := OnlineUserMap[req.Data.ToUserId]
	if toUserId == nil {
		GetFailResp(coon, 500, "用户不在线")
		return
	}
	GetSuccessResp(toUserId, req.Data.Content)
	GetSuccessResp(coon, "发送成功")
	chatHistory := model.FriendReq{
		SendId: userId,
	}
	dao.Create(&chatHistory)
}

func GenRoomId(sendId uint, receiveId uint) uint {
	min := sendId
	max := receiveId
	if min > max {
		max = sendId
		min = receiveId
	}
	return min*1000000 + max
}

func GetFailResp(conn *websocket.Conn, code int, msg string) {
	resp := WsResp{
		Code: code,
		Msg:  msg,
		Data: nil,
	}
	respByte, _ := json.Marshal(resp)
	_ = conn.WriteMessage(websocket.TextMessage, respByte)
}
func GetSuccessResp(conn *websocket.Conn, data interface{}) {
	resp := WsResp{
		Code: 200,
		Msg:  "ok",
		Data: data,
	}
	respByte, _ := json.Marshal(resp)
	_ = conn.WriteMessage(websocket.TextMessage, respByte)
}

func FindChat(c *gin.Context) {

}
